package com.demo.Interceptor;

import com.demo.common.BaseContext;
import com.demo.common.RedisConstants;
import com.demo.exception.LoginFailException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@RequiredArgsConstructor
public class UserLoginInterceptor implements HandlerInterceptor {
    private final RedisTemplate redisTemplate;

    /***
     * 在请求处理之前进行调用(Controller方法调用之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("执行了拦截器的preHandle方法");
        try {
            String token = request.getHeader("token");
            System.out.println(token);
            String tokenKey = RedisConstants.LOGIN_CODE_KEY + token;
            Integer userId = (Integer) redisTemplate.opsForValue().get(tokenKey);
            if (userId != null) {
                redisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
                BaseContext.setCurrentId(userId);
                return true;
            }
            response.sendRedirect(request.getContextPath() + "/user/login");
            response.setStatus(0);
            return false;
        } catch (LoginFailException e) {
            log.info(e.getCause().toString());
            response.sendRedirect(request.getContextPath() + "/user/login");
        }
        return false;
        //如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
        //如果设置为true时，请求将会继续执行后面的操作
    }

    /***
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("执行了拦截器的postHandle方法");
    }

    /***
     * 整个请求结束之后被调用，也就是在DispatchServlet渲染了对应的视图之后执行（主要用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("执行了拦截器的afterCompletion方法");
    }
}




